import axios from 'axios'

import qs from 'qs'

import { config } from './config'

import { ElMessage } from 'element-plus'

const { result_code, login_code, keyan_code, base_url } = config

// export const PATH_URL = 'http://39.107.139.52:8989'
export const PATH_URL = 'https://ivd-api.cndatamed.com' // ivd接口地址 
// export const PATH_URL = 'https://blb-api.rongchengshuke.com' // 测试地址

// 创建axios实例
const service = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    config['localhostHref'] = window.location.href // 可以判断当前接口是在哪个页面调用的
    if (
      config.method === 'post' &&
      config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }
    // ;(config.headers)['Token'] = 'test test'
    // get参数编码
    if (config.method === 'get' && config.params) {
      config.url = config.url
      config.params = {}
    }
    return config
  },
  (error) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response) => {

    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.data.code === login_code || response.data.code == 888) {
      // 需要登录
      localStorage.removeItem("token");
    } else if (response.data.code === result_code) {
      return response.data
    } else if ([403, 404, 500, null, undefined].indexOf(response.data.code) > -1) {
    } else if (!response.config?.noErrorHint) {
      ElMessage.error(response.data.message || response.data.msg)
    }
    return response?.data
  },
  (error) => {
    const { status } = error?.response || {}
    if ([403, 404, 500].indexOf(status) > -1) {
    }
    const { noErrorHint } = error?.config || {}
    if (error.message === 'canceled' || noErrorHint) {
      return Promise.reject(error)
    } else {
      console.log('err', error)
      ElMessage.error(error.message)
      return Promise.reject(error)
    }
  }
)

export { axios, service }
